<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SVG Chart to Image Download</title>
    <!-- 引入 ECharts -->
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.2.1/dist/echarts.min.js"></script>
    <!-- 引入 html2canvas -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
</head>
<body>
<!-- 渲染 ECharts 图表的容器 -->
<div id="chartContainer" style="width: 600px; height: 400px;"></div>
<!-- 用于下载图片的按钮 -->
<button id="downloadBtn">Download Chart as Image</button>

<script>
  // 创建 ECharts 图表
  var chartDom = document.getElementById('chartContainer');
  var myChart = echarts.init(chartDom, null, {
    renderer: 'svg',
  });
  var option;

  // 使用示例数据
  option = {
    xAxis: {
      type: 'category',
      data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      data: [820, 932, 901, 934, 1290, 1330, 1320],
      type: 'line'
    }]
  };

  // 设置图表配置项并渲染
  if (option && typeof option === 'object') {
    myChart.setOption(option);
  }

  // 添加点击事件，将图表转换为图片并下载
  document.getElementById('downloadBtn').addEventListener('click', function() {
    html2canvas(chartDom, {
      scale: 2, // 放大倍数，可根据需要调整
      width: chartDom.clientWidth, // 设置画布宽度为图表容器的宽度
      height: chartDom.clientHeight,
      onrendered: function(canvas) {
        var link = document.createElement('a');
        link.download = 'chart_image.png';
        link.href = canvas.toDataURL();
        link.click();
      }
    });
  });
</script>
</body>
</html>
